package com.ant.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ant.storage.mapper.AllocationMapper;
import com.ant.storage.mapper.UserMapper;
import com.ant.storage.pojo.Department;
import com.ant.storage.pojo.User;
import com.ant.storage.service.IDepartmentService;
import com.ant.storage.service.IUserService;
import com.ant.storage.utils.DingDingUtil;
import com.ant.storage.common.ResultVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiV2DepartmentListsubRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiV2DepartmentListsubResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService{

    @Autowired
    IDepartmentService departmentService;

    @Autowired(required = false)
    AllocationMapper allocationMapper;

    @Autowired(required = false)
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDeptId() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
        OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
        req.setDeptId(1L);
        req.setLanguage("zh_CN");
        OapiV2DepartmentListsubResponse rsp = client.execute(req,DingDingUtil.obtainToken());
        JSONArray params = JSON.parseArray(JSONObject.parseObject(rsp.getBody()).getString("result"));
        List<Object> dept_id_list = new ArrayList<>();
        for (Object param : params) {
            Department department = new Department();
            JSONObject object = JSONObject.parseObject(param.toString());
            dept_id_list.add(object.get("dept_id"));
            department.setDepartmentId(Integer.valueOf(object.get("dept_id").toString()));
            department.setDepartmentName(object.get("name").toString());
            department.setParentId(Integer.valueOf(object.get("parent_id").toString()));
            UpdateWrapper<Department> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("department_id",object.get("dept_id"));
            departmentService.saveOrUpdate(department);
        }
        while (true){
            dept_id_list = listQueryDeptId(dept_id_list);
            if(dept_id_list == null){
                break;
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    List<Object> listQueryDeptId(List<Object> list) throws ApiException {
        List<Object> deptList = new ArrayList<>();
        for(Object obj:list){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/department/listsub");
            OapiV2DepartmentListsubRequest req = new OapiV2DepartmentListsubRequest();
            req.setDeptId(Long.parseLong(obj.toString()));
            req.setLanguage("zh_CN");
            OapiV2DepartmentListsubResponse rsp = client.execute(req,DingDingUtil.obtainToken());
            JSONArray params = JSON.parseArray(JSONObject.parseObject(rsp.getBody()).getString("result"));
            for (Object param : params) {
                Department department = new Department();
                JSONObject object = JSONObject.parseObject(param.toString());
                department.setDepartmentId(Integer.valueOf(object.get("dept_id").toString()));
                department.setDepartmentName(object.get("name").toString());
                department.setParentId(Integer.valueOf(object.get("parent_id").toString()));
                UpdateWrapper<Department> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("department_id",object.get("dept_id"));
                departmentService.saveOrUpdate(department);
                deptList.add(object.get("dept_id"));
            }
        }
        if(deptList.size() == 0){
            return null;
        }else {
            return deptList;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser() throws ApiException {
        List<Department>list = departmentService.list();
        String access_token = DingDingUtil.obtainToken();
        allocationMapper.addToken(access_token);
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
        for(Department department:list){
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(Long.valueOf(department.getDepartmentId()));
            req.setCursor(0L);
            req.setSize(100L);
            OapiV2UserListResponse rsp = client.execute(req,access_token);
            JSONArray params = JSON.parseArray(JSONObject.parseObject(JSON.parseObject(rsp.getBody()).getString("result")).getString("list"));
            for(Object param:params){
                User user = new User();
                JSONObject object = JSONObject.parseObject(param.toString());
                user.setDept_id(department.getDepartmentId());
                user.setUser_name(object.getString("name"));
                user.setUser_mobile(Long.parseLong(object.getString("mobile")));
                user.setUser_title(object.getString("title"));
                user.setUserid(object.getString("userid"));
                user.setUnionid(object.getString("unionid"));
                user.setUser_type(1);
                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("userid",object.getString("userid"));
                this.saveOrUpdate(user,updateWrapper);
            }
        }
    }

    @Override
    public User queryUserId(String name, Long tel) {
        User user = userMapper.telQueryUserId(tel);
        if(user == null){
            return userMapper.nameQueryUserId(name);
        }else{
            return user;
        }
    }

    @Override
    public User findQueryUserId(String id) {
         return userMapper.QueryUserId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDeptAndUser(){
        userMapper.deleteDept();
        userMapper.deleteUser();
    }

    @Override
    public ResultVo queryUser(String user_name, String user_mobile) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_mobile",user_mobile);
        List<User> list = this.list(queryWrapper);
        if(list != null){
            return ResultVo.success("ok",list);
        }
        QueryWrapper<User> queryWrapper01 = new QueryWrapper<>();
        queryWrapper01.eq("user_name",user_name);
        List<User> list01 = this.list(queryWrapper01);
        return ResultVo.success("ok",list01);
    }

    @Override
    public ResultVo queryUserOne(String userId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",userId);
        User user = this.getOne(queryWrapper);
        return ResultVo.success("ok",user);
    }
}
